package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.bwie.client.user.UserFeignClient;
import com.bwie.pojo.User;
import com.bwie.service.AuthService;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Mikey
 * @Date: 2025/9/9 09:46
 * @Description:
 **/
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public R login(User user) {
        //远程调用通过手机号查看用户是否存在
        User loginUser = userFeignClient.getUserByPhone(user.getPhone());
        //用户是否存在
        if(loginUser==null){
            return R.ERROR(500,"用户不存在");
        }

        //存在判断验证码是否正确 去redis中查询
        String redisCode = redisTemplate.opsForValue().get(loginUser.getPhone());
        if(redisCode==null){
            //过期
            return R.ERROR(500,"验证码已过期,请重新发送");
        }

        //判断是否正确
        if(!user.getCode().equals(redisCode)){
            return R.ERROR(500,"验证码错误,请重新输入");
        }

        //校验完成  进行jwts加密
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "ashujio56785678")
                .setExpiration(new Date(System.currentTimeMillis() + 720000))
                .setId(loginUser.getId() + "")
                .claim("id", loginUser.getId())
                .claim("username", loginUser.getUsername())
                .compact();

        //将token存储进redis缓存中
        redisTemplate.opsForValue().set("token-"+loginUser.getId(),token,15,TimeUnit.MINUTES);

        //将token设置给user返回给前端
        loginUser.setToken(token);
        //将user的密码设置为空 隐私性
        loginUser.setPassword(null);
        return R.OK(loginUser);
    }

    @Autowired
    HttpServletRequest request;
    @Override
    public R sendCode(User user) {
        //远程调用通过手机号查看用户是否存在
        User loginUser = userFeignClient.getUserByPhone(user.getPhone());

        //用户是否存在
        if(loginUser==null){
            return R.ERROR(500,"用户不存在");
        }

        String redisLong = redisTemplate.opsForValue().get("lock" + loginUser.getPhone());
        if(redisLong!=null){
            return R.ERROR(500,"请勿频繁登录，一个手机号5分钟只能发送1次");
        }


        //生成4位随机验证码
        String code= RandomUtil.randomNumbers(4);
        boolean flag=false;
        //用户存在发送验证码
        Boolean aBoolean = MobileMessageUtil.sendMobileMessage(loginUser.getPhone(), code);
        if(aBoolean){
            //发送成功 修改初始值
            flag=aBoolean;
            //	验证码以手机号为key保存到redis当中，有效时间5分钟
            redisTemplate.opsForValue().set(loginUser.getPhone(),code,5, TimeUnit.MINUTES);

            //验证码一个手机号5分钟只能发送1次
            redisTemplate.opsForValue().set("lock"+loginUser.getPhone(),code,5,TimeUnit.MINUTES);

            //发送成功
            return R.OK();
        }

        //定义一个次数
        int count=0;

        //发送失败重试
        while (flag && count<3){
            count++;
            System.out.println("第"+count+"次重试发送");
            aBoolean=MobileMessageUtil.sendMobileMessage(loginUser.getPhone(), code);
            if(aBoolean){
                flag=true;
                redisTemplate.opsForValue().set(loginUser.getPhone(),code,5, TimeUnit.MINUTES);
                redisTemplate.opsForValue().set("lock"+loginUser.getPhone(),code,5,TimeUnit.MINUTES);
                return R.OK();
            }
        }

        if(flag){
            //切换服务商再进行尝试


        }
        return R.ERROR(500,"已重试"+count+"次,发送失败!");
    }
}
